import auth from '@/plugins/auth'
import router, { constantRoutes, dynamicRoutes } from '@/router'
import { getRouters } from '@/api/menu'
import Layout from '@/layout/index'
import ParentView from '@/components/ParentView'
import InnerLink from '@/layout/components/InnerLink'
import { deepClone } from '@/utils/index'

// 匹配views里面所有的.vue文件
const modules = import.meta.glob('./../../views/**/*.vue')

const usePermissionStore = defineStore('permission', {
	state: () => ({
		// 完整路由表
		routes: [],
		// 动态路由部分
		addRoutes: [],
		// 默认路由（顶部导航使用）
		defaultRoutes: [],
		// 顶部导航路由
		topbarRouters: [],
		// 侧边栏路由
		sidebarRouters: []
		// sidebarRouters: constantRoutes
	}),
	actions: {
		// 设置完整路由表
		setRoutes(routes) {
			this.addRoutes = routes
			// 合并静态路由和动态路由
			this.routes = constantRoutes.concat(routes)
		},
		// 设置默认路由（用于顶部导航）
		setDefaultRoutes(routes) {
			this.defaultRoutes = constantRoutes.concat(routes)
		},
		// 设置顶部导航路由
		setTopbarRoutes(routes) {
			this.topbarRouters = routes
		},
		// 设置侧边栏路由
		setSidebarRouters(routes) {
			this.sidebarRouters = routes
		},
		// 生成动态路由
		generateRoutes(roles) {
			return new Promise((resolve) => {
				// 向后端请求路由数据
				getRouters().then((res) => {
					res.data.forEach((item, index) => {
						if (item.name == 'Demo') {
							res.data.splice(index, 1)
						}
					})
					// 深拷贝路由数据
					const sdata = deepClone(res.data)
					const rdata = deepClone(res.data)
					const defaultData = deepClone(res.data)
					// 解析路由
					// 侧边栏路由
					const sidebarRoutes = filterAsyncRouter(sdata)
					// 生成扁平化的子路由列表
					const rewriteRoutes = filterAsyncRouter(rdata, false, true)
					// 默认路由
					const defaultRoutes = filterAsyncRouter(defaultData)
					// 动态路由遍历，验证是否具备权限
					// FIXME
					const asyncRoutes = filterDynamicRoutes(dynamicRoutes, sidebarRoutes)
					// 添加动态路由
					asyncRoutes.forEach((route) => {
						router.addRoute(route)
					})
					// 更新 Store 中的路由状态
					this.setRoutes(rewriteRoutes)
					this.setSidebarRouters(constantRoutes.concat(sidebarRoutes))
					this.setDefaultRoutes(sidebarRoutes)
					this.setTopbarRoutes(defaultRoutes)
					// 返回解析后的路由
					resolve(rewriteRoutes)
				})
			})
		}
	}
})

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
	return asyncRouterMap.filter((route) => {
		if (type && route.children) {
			// 扁平化子路由
			route.children = filterChildren(route.children)
		}
		if (route.component) {
			// Layout ParentView 组件特殊处理
			// 映射 Layout 组件
			if (route.component === 'Layout') {
				route.component = Layout
			} else if (route.component === 'ParentView') {
				// 映射 ParentView 组件
				route.component = ParentView
			} else if (route.component === 'InnerLink') {
				// 映射 InnerLink 组件
				route.component = InnerLink
			} else {
				// 动态加载其他组件
				route.component = loadView(route.component)
			}
		}
		if (route.children != null && route.children && route.children.length) {
			route.children = filterAsyncRouter(route.children, route, type)
		} else {
			// 没有子路由时删除多余字段
			delete route['children']
			delete route['redirect']
		}
		return true
	})
}

/* 处理嵌套的路由结构，将子路由按照一定规则进行平铺处理，生成扁平化的子路由列表，同时根据父路由调整子路由的路径 */
function filterChildren(childrenMap, lastRouter = false) {
	var children = []
	childrenMap.forEach((el, index) => {
		if (el.children && el.children.length) {
			if (el.component === 'ParentView' && !lastRouter) {
				el.children.forEach((c) => {
					c.path = el.path + '/' + c.path
					if (c.children && c.children.length) {
						children = children.concat(filterChildren(c.children, c))
						return
					}
					children.push(c)
				})
				return
			}
		}
		if (lastRouter) {
			// 拼接父路径
			el.path = lastRouter.path + '/' + el.path
		}
		children = children.concat(el)
	})
	return children
}

// 动态路由遍历，验证是否具备权限,支持基于权限（permissions）或角色（roles）的验证
export function filterDynamicRoutes(routes, sidebarRoutes) {
	/* 
routes: 动态路由
sidebarRoutes: 侧边栏路由
*/
	const res = []
	routes.forEach((route) => {
		if (route.permissions) {
			if (auth.hasPermiOr(route.permissions)) {
				res.push(route)
			}
		} else if (route.roles) {
			if (auth.hasRoleOr(route.roles)) {
				res.push(route)
			}
		} else if (!route.roles) {
			/*
			动态路由没有配置权限;
			当请求的侧边栏路由的与当前路由的path相同时，将该路由添加到动态路由中
			 */
			sidebarRoutes.forEach((sideItem) => {
				if (sideItem.path === route.path) {
					res.push(route)
				}
			})
		}
	})
	return res
}

export const loadView = (view) => {
	let res
	for (const path in modules) {
		const dir = path.split('views/')[1].split('.vue')[0]
		if (dir === view) {
			res = () => modules[path]()
		}
	}
	return res

}

export default usePermissionStore
